package yxy.game.pm2.module.union.war;

import java.util.ArrayList;
import java.util.HashSet;

import org.joda.time.DateTime;

import yxy.apple.util.redisson.RedisException;
import yxy.game.pm2.bean.module.BaseGameRedisBean;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.module.union.war.UnionWarHandle.UnionWarStateEnum;

/** 联盟战总模块 */
//记录 参战联盟列表，对阵表 等
public class UnionWarModule extends BaseGameRedisBean {
	// bean==========================================================================

	private UnionWarStateEnum state;
	private DateTime updateTime;
	private HashSet<String> unionSet = new HashSet<>();// 参战联盟code
	private ArrayList<UnionWarGroup> groups = new ArrayList<>();// 对阵表
	private int areaGroupId; //战区id

	public int getAreaGroupId() {
		return areaGroupId;
	}

	public void setAreaGroupId(int areaGroupId) {
		this.areaGroupId = areaGroupId;
	}

	public UnionWarStateEnum getState() {
		return state;
	}

	public void setState(UnionWarStateEnum state) {
		this.state = state;
	}

	public DateTime getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(DateTime updateTime) {
		this.updateTime = updateTime;
	}

	public HashSet<String> getUnionSet() {
		return unionSet;
	}

	public void setUnionSet(HashSet<String> unionSet) {
		this.unionSet = unionSet;
	}

	public ArrayList<UnionWarGroup> getGroups() {
		return groups;
	}

	public void setGroups(ArrayList<UnionWarGroup> groups) {
		this.groups = groups;
	}

	// func==========================================================================

	// redis==========================================================================

	static public String key(int areaGroupId) {
		return String.format("UNIONWAR:%s", areaGroupId);
	}

	public void set() {
		try {
			setv(key(getAreaGroupId()), this);
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	static public UnionWarModule get(int areaGroupId) {
		try {
			UnionWarModule module = getv(key(areaGroupId));
			if (module == null) {
				module = create(areaGroupId);
				module.set();
			}
			return module;
		} catch (RedisException e) {
		}
		return null;
	}

	private static UnionWarModule create(int areaGroupId) {
		UnionWarModule module = new UnionWarModule();
		module.setAreaGroupId(areaGroupId);
		module.setUpdateTime(DateTime.now());
		module.setState(UnionWarStateEnum.TRUCE);
		return module;
	}

	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getAreaGroupId()));
	}

	@Override
	public boolean tryLock() throws InterruptedException {
		return super.tryLock();
	}

	public static RedisLock lock(int areaGroupId) {
		return getLock(String.format("lock:%s", key(areaGroupId)));
	}
}
